<template>
    <div class="embroidery-test">

        <!-- <div class="block embroidery-need" name="需求">
            <p>匹配线色，默认 15 色循环，可修改</p>
            <p>刺绣在刺绣框内可移动，不可旋转（通过设定空针将 DST 起始点放在刺绣框中心）</p>
            <p>生成刺绣预览图</p>
            <p>输出符合生产要求的 DST 文件、线杆x颜色文件</p>
            <p>生成线框图用于生产定位</p>
            <p>验证 DST 文件、线杆x颜色文件可以自动传输至 DT.NET 后直接用于生产</p>
            <p>验证TCF/TBF/DST/DSB/DSZ/U)*格式文件的可读，可写，携带颜色信息</p>
        </div>

        <div class="block embroidery-need" name="讨论点">
            <p>当刺绣框可拖动时，线框图和模特图的映射关系</p>
            <p>同一个面多个刺绣区域显示冲突</p>
        </div> -->

        <div class="embroidery-edit">

            <div class="embroidery-design" ref="warper">
                <img v-if="surfaceActive" :src="$getImageUrl(surfaceActive.mask_image, 'largest')" alt="">

                <div class="embroidery-piece">
                    <span v-for="(surface,index) in surface_list" :key="index" :class="{active:surface_index == index}" @click="surface_index = index">
                        {{surface.surface_name}}
                    </span>
                </div>

                <div class="embroidery-surface" v-if="surfaceActive" :style="getSurfaceStyle(surfaceActive)">
                    <div class="embroidery-warper" v-for="(warper,index) in surfaceActive.warper" :key="index" :style="getOuterStyle(surfaceActive,warper)" :class="{active: index == warper_index}" @mousedown="onMouseDown('outer',warper,$event)">
                        <svg viewBox="0,0,80,80">
                            <line x1="0" y1="40" x2="80" y2="40" stroke-width="1" stroke="#000" shape-rendering="crispEdges" />
                            <line x1="40" y1="0" x2="40" y2="80" stroke-width="1" stroke="#000" shape-rendering="crispEdges" />
                        </svg>
                        <div class="embroidery-inner" v-for="(pattern,idx) in warper.patterns" :key="idx" :style="getInnerStyle(warper,pattern)" :class="{active:warper == warperActive}" @mousedown.stop="onMouseDown('inner', pattern,$event)">
                            <EmbroideryPreview :stitches="pattern.stitches" :colors="pattern.colors" />
                        </div>
                    </div>
                </div>

            </div>

            <!-- 款式区 -->
            <div class="embroidery-info">

                <div class="embroidery-spu">
                    <span>衣服款式</span>
                    <input type="text" v-model="spu">
                    <button @click=loadSpu()>加载</button>
                </div>

                <div class="block embroidery-box" name="绣框" v-if="surfaceActive">
                    <ul>
                        <li v-for="(item,index) in surfaceActive.warper" :key="index" :class="{active : warper_index == index}" @click="setWarper(index)">
                            {{[item.w,item.h].join('-') }}
                        </li>
                    </ul>
                </div>

                <div class="embroidery-pattern" v-if="warperActive">
                    <div class="embroidery-pattern-title">
                        <span>版带</span>
                        <EmbroideryText @upload="onUpload($event)" />
                        <EmbroideryUploader @upload="onUpload($event)" />
                    </div>
                    <ul>
                        <li v-for="(pattern,index) in warperActive.patterns" :key="index" :class="{active : pattern_index == index}" @click="setPattern(index)">
                            <EmbroideryPreview :stitches="pattern.stitches" :colors="pattern.colors" />
                        </li>
                    </ul>
                </div>

                <div class="embroidery-colors" v-if="patternActive">
                    <el-popover placement="bottom" width="256" trigger="click" v-for="(item,index) in patternColors" :key="index">
                        <div class="input-color" slot="reference">
                            <em :style="{ backgroundColor: item.hex }"></em>
                            <i class="iconfont icon-xia"></i>
                        </div>
                        <div class="input-picker">
                            <span v-for="(color,idx) in colors" :key="idx" :style="{ backgroundColor: color.hex }" @click="setColor(index,color)"></span>
                        </div>
                    </el-popover>
                </div>

                <div class="embroidery-message" v-if="warperActive">

                    <p v-if="surfaceActive">canvas size: {{[surfaceActive.canvas_width,surfaceActive.canvas_height].join('x')}}</p>
                    <p v-if="warperActive">outer size: {{[warperActive.w,warperActive.h].join('x')}}</p>
                    <p v-if="patternActive">inner size:{{[patternActive.w,patternActive.h].join('x')}}</p>

                    <template v-if="warperActive">
                        <UxInputSlider name="outer x" v-model="warperActive.x" :max="surfaceActive.canvas_width - warperActive.w" :min="0" :precision="2" :step="0.1" />
                        <UxInputSlider name="outer y" v-model="warperActive.y" :max="surfaceActive.canvas_height - warperActive.h" :min="0" :precision="2" :step="0.1" />
                        <UxInputSlider name="outer rotate" v-model="warperActive.r" :max="360" :min="0" :precision="2" :step="0.1" />
                    </template>

                    <template v-if="patternActive">
                        <UxInputSlider name="inner x" v-model="patternActive.x" :max="warperActive.w - patternActive.w" :min="0" :precision="2" :step="0.1" />
                        <UxInputSlider name="inner y" v-model="patternActive.y" :max="warperActive.h - patternActive.h" :min="0" :precision="2" :step="0.1" />
                        <UxInputSlider name="inner r" v-model="patternActive.r" :max="360" :min="0" :precision="2" :step="1" />
                    </template>

                </div>

                <div class="embroidery-output">
                    <button @click="doOutput()">输出</button>
                </div>

            </div>

        </div>

    </div>
</template>
<script>
import { Pattern, colors } from "@/utils/EmbroideryPattern.js";

export default {
    name: "LogisticsText",
    data () {
        return {
            spu: '130U007',
            surface_list: [],
            surface_index: 0,
            warper_index: 0,
            pattern_index: 0,
            colors: colors,
            mouse: null,
        };
    },
    computed: {
        surfaceActive () { return this.surface_list[this.surface_index] },
        warperActive () { return this.surfaceActive ? this.surfaceActive.warper[this.warper_index] : undefined },
        patternActive () { return this.warperActive ? this.warperActive.patterns[this.pattern_index] : undefined },
        patternColors () { return this.patternActive ? this.patternActive.colors : [] },
        outerStyle () {
            if (this.warperActive) {
                return {
                    width: 100 * this.warperActive.w / this.surfaceActive.canvas_width + '%',
                    height: 100 * this.warperActive.h / this.surfaceActive.canvas_height + '%',
                    left: 100 * this.warperActive.x / this.surfaceActive.canvas_width + '%',
                    top: 100 * this.warperActive.y / this.surfaceActive.canvas_height + '%',
                    transform: `rotate(${this.warperActive.r}deg)`,
                }
            } else {
                return undefined
            }
        },
        innerStyle () {

            if (this.patternActive) {

                // 容器中心点坐标
                const outer = {
                    x: this.warperActive.x + 0.5 * this.warperActive.w,
                    y: this.warperActive.y + 0.5 * this.warperActive.h,
                }
                // 刺绣的中心点相对容器中心点位置
                const offset = {
                    x: this.patternActive.x + 0.5 * this.patternActive.w - 0.5 * this.warperActive.w,
                    y: this.patternActive.y + 0.5 * this.patternActive.h - 0.5 * this.warperActive.h,
                }

                const rotate = this.coordinateRotation(offset.x, offset.y, 0, 0, this.warperActive.r)

                return {
                    width: 100 * this.patternActive.w / this.surfaceActive.canvas_width + '%',
                    height: 100 * this.patternActive.h / this.surfaceActive.canvas_height + '%',
                    left: 100 * (outer.x + rotate.x - 0.5 * this.patternActive.w) / this.surfaceActive.canvas_width + '%',
                    top: 100 * (outer.y + rotate.y - 0.5 * this.patternActive.h) / this.surfaceActive.canvas_height + '%',
                    transform: `rotate(${this.warperActive.r}deg)`,
                }
            }

        }
    },
    methods: {
        onUpload (pattern) {

            if (this.warperActive) {
                const size = pattern.getBounds()
                const width = size.right - size.left;
                const height = size.bottom - size.top

                this.warperActive.patterns.push({
                    stitches: pattern.stitches,
                    colors: pattern.colors,
                    x: (this.warperActive.w - width) / 2,
                    y: (this.warperActive.h - height) / 2,
                    r: 0,
                    w: width,
                    h: height
                })
            }

        },
        // 鼠标点击事件
        onMouseDown (action, handle, event) {

            event.preventDefault();
            event.stopPropagation();

            const warper = this.$refs.warper.getBoundingClientRect();

            const touch = (event.targetTouches || [])[0];
            const clientX = touch ? touch.clientX : event.clientX;
            const clientY = touch ? touch.clientY : event.clientY;

            this.mouse = {
                action: action,
                handle: handle,
                start: new Date().getTime(),
                clientX: clientX,
                clientY: clientY,
                x: handle.x,
                y: handle.y,
                width: warper.width,
                height: warper.height,
            };


        },
        onMousemove (event) {

            if (!this.mouse) { return; }

            event.preventDefault();
            event.stopPropagation();

            const touch = (event.targetTouches || [])[0];
            const clientX = touch ? touch.clientX : event.clientX;
            const clientY = touch ? touch.clientY : event.clientY;
            const offsetX = clientX - this.mouse.clientX;
            const offsetY = clientY - this.mouse.clientY;


            if (this.mouse.action == 'outer') {

                const x = this.mouse.x + this.surfaceActive.canvas_width * offsetX / this.mouse.width
                const y = this.mouse.y + this.surfaceActive.canvas_height * offsetY / this.mouse.height

                this.mouse.handle.x = Math.max(0, Math.min(this.surfaceActive.canvas_width - this.mouse.handle.w, x))
                this.mouse.handle.y = Math.max(0, Math.min(this.surfaceActive.canvas_height - this.mouse.handle.h, y))

            } else if (this.mouse.action == 'inner') {
                const rotate = this.coordinateRotation(offsetX, offsetY, 0, 0, -this.warperActive.r)
                const x = this.mouse.x + this.surfaceActive.canvas_width * rotate.x / this.mouse.width
                const y = this.mouse.y + this.surfaceActive.canvas_height * rotate.y / this.mouse.height

                this.mouse.handle.x = Math.max(0, Math.min(this.warperActive.w - this.mouse.handle.w, x))
                this.mouse.handle.y = Math.max(0, Math.min(this.warperActive.h - this.mouse.handle.h, y))
            }

        },
        onMouseup (event) {
            if (this.mouse) {
                event.preventDefault();
                event.stopPropagation();
                this.mouse = null;
            }
        },
        // 坐标旋转
        // x,y 点的坐标
        // xo,yo 镜像原点
        // r 旋转角度
        coordinateRotation (x, y, ox, oy, r) {
            const radians = (-r * Math.PI) / 180;
            const cos = Math.cos(radians);
            const sin = Math.sin(radians);

            const x1 = x - ox;
            const y1 = y - oy;
            const xr = x1 * cos + y1 * sin;
            const yr = y1 * cos - x1 * sin;

            return {
                x: Math.round(xr + ox),
                y: Math.round(yr + oy)
            };
        },



        colorRgb (color) {
            var sColor = color.toLowerCase();
            //十六进制颜色值的正则表达式
            var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
            // 如果是16进制颜色
            if (sColor && reg.test(sColor)) {
                if (sColor.length === 4) {
                    var sColorNew = "#";
                    for (var i = 1; i < 4; i += 1) {
                        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                    }
                    sColor = sColorNew;
                }
                //处理六位的颜色值
                var sColorChange = [];
                for (var i = 1; i < 7; i += 2) {
                    sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
                }
                return sColorChange
            }
            return [];
        },

        getSurfaceStyle (surface) {
            return {
                width: 100 * surface.canvas_width / surface.outer_width + '%',
                height: 100 * surface.canvas_height / surface.outer_height + '%',
                left: 100 * surface.canvas_left / surface.outer_width + '%',
                top: 100 * surface.canvas_top / surface.outer_height + '%',
                transform: `rotate(${surface.canvas_rotate}deg)`,
            }
        },
        getOuterStyle (surface, warper) {

            return {
                width: 100 * warper.w / surface.canvas_width * surface.scale + '%',
                height: 100 * warper.h / surface.canvas_height * surface.scale + '%',
                left: 100 * warper.x / surface.canvas_width * surface.scale + '%',
                top: 100 * warper.y / surface.canvas_height * surface.scale + '%',
                transform: `rotate(${warper.r}deg)`,
            }
        },

        getInnerStyle (warper, pattern) {
            return {
                width: 100 * pattern.w / warper.w + '%',
                height: 100 * pattern.h / warper.h + '%',
                left: 100 * pattern.x / warper.w + '%',
                top: 100 * pattern.y / warper.h + '%',
                transform: `rotate(${pattern.r}deg)`,
            }
        },

        getColor (color) {
            return `rgb(${[color.r, color.g, color.b].join(',')})`
        },

        setColor (index, event) {
            if (this.patternActive) {
                const colors = this.patternActive.colors.slice(0)
                colors[index] = event;
                this.patternActive.colors = colors
            }
        },


        setPattern (index) {
            this.pattern_index = index;
        },
        setWarper (index) {
            this.warper_index = index;
        },

        async doRequest (req) {


        },

        // 生产
        doOutput () {


            const url = 'http://localhost:8000/batchDrawEmbroideryFiles'

            const request = {
                surface: []
            }

            // 回调
            const callback = (res) => {
                console.log(res);
            }

            this.surface_list.map(surface => {
                const used = surface.warper.filter(i => i.patterns.length > 0)
                used.length > 0 && request.surface.push({
                    ...surface,
                    warper: used
                })
            });

            const xhr = new XMLHttpRequest(); // 新建XMLHttpRequest对象
            xhr.onreadystatechange = function () { // 状态发生变化时，函数被回调
                if (xhr.readyState === 4) { // 成功完成
                    // 判断响应结果:
                    if (xhr.status === 200) {
                        // 成功，通过responseText拿到响应的文本:
                        callback(xhr.responseText);
                    } else {
                        // 失败，根据响应码判断失败原因:
                        callback(xhr.status);
                    }
                } else {
                    // HTTP请求还在继续...
                }
            }

            // 发送请求:
            xhr.open('POST', url);
            xhr.setRequestHeader('content-type', "application/json");
            xhr.send(JSON.stringify(request));


        },
        test () {
            const pattern = new Pattern();
            pattern.stitches = [
                [0, 0, 0],
                [0, 200, 0],
                [200, 200, 0],
                [200, 0, 0],
                [0, 0, 0],
                [1, 1, 0],
                [1, -1, 0],
            ]

            pattern.setColorsByCount(1);
            this.warper_index = 2;
            this.onUpload(pattern)
        },

        loadSpu (callback) {
            this.$http("Designer.getInfo", this.spu).then(res => {
                const data = res.data || {}
                const pieces = data.piece_list || []
                const surface = new Map(pieces.map(piece => [piece.surface_name, piece]))

                this.surface_list = Array.from(surface.values()).map(item => {


                    const scale = 0.5;
                    const warper = [
                        { w: 300, h: 600, x: 450, y: 450, r: 0, patterns: [] },
                        { w: 500, h: 500, x: 350, y: 350, r: 0, patterns: [] },
                        { w: 800, h: 800, x: 200, y: 200, r: 0, patterns: [] },
                        { w: 1000, h: 1000, x: 100, y: 100, r: 0, patterns: [] },
                        { w: 2500, h: 2500, x: 100, y: 100, r: 0, patterns: [] }
                    ]

                    warper.map(i => {
                        i.x = (1600 - i.w * scale) / 2;
                        i.y = (1600 - i.h * scale) / 2;
                    })

                    return {
                        surface_name: item.surface_name,
                        mask_image: item.mask_image,
                        outer_width: item.outer_width,
                        outer_height: item.outer_height,
                        canvas_left: 200,
                        canvas_top: 200,
                        canvas_width: 1600,
                        canvas_height: 1600,
                        scale: scale,
                        // warper: ['Front Side', 'Back Side'].indexOf(item.surface_name) >= 0 ? warper.slice(2, 4) : warper.slice(0, 2)
                        warper: warper
                    }
                })

                callback && callback()
            })
        },
    },
    mounted () {
        window.addEventListener('mousemove', this.onMousemove, false); // 鼠标移动
        window.addEventListener('mouseup', this.onMouseup, false); // 鼠标弹起
        window.addEventListener('touchmove', this.onMousemove, { passive: false }); // 鼠标移动
        window.addEventListener('touchend', this.onMouseup, { passive: false }); // 鼠标弹起

        // this.loadSpu(() => this.test());
        this.loadSpu();
    },
    // 销毁
    beforeDestroy: function () {
        window.removeEventListener('mousemove', this.onMousemove); // 鼠标移动
        window.removeEventListener('mouseup', this.onMouseup); // 鼠标弹起
        window.removeEventListener('touchmove', this.onMousemove); // 鼠标移动
        window.removeEventListener('touchend', this.onMouseup); // 鼠标弹起
    }
};
</script>
<style lang="scss" scoped>
.embroidery-test {
    padding: 20px;
    width: 100%;
    box-sizing: border-box;
}

.embroidery-edit {
    display: flex;
    align-items: flex-start;

    .embroidery-design {
        width: 60%;
        margin-right: 20px;
        border: 1px solid #ddd;
        position: relative;
        overflow: hidden;
        &::before {
            content: '';
            display: block;
            padding-bottom: 100%;
        }
        & > div {
            position: absolute;
        }

        & > img {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }

        .embroidery-piece {
            position: absolute;
            left: 50%;
            top: 2px;
            transform: translateX(-50%);
            display: flex;

            span {
                margin: 5px;
                border: 1px solid #ddd;
                background-color: #fff;
                padding: 5px 10px;
                border-radius: 20px;
                white-space: nowrap;
                cursor: pointer;

                &:hover {
                    color: #b32f61;
                }

                &.active {
                    color: #b32f61;
                    border-color: #b32f61;
                }
            }
        }

        .embroidery-surface {
            position: absolute;
            background-color: rgba($color: #000000, $alpha: 0.1);
        }

        .embroidery-outer {
        }

        .embroidery-warper {
            position: absolute;
            pointer-events: none;
            svg {
                display: none;
                pointer-events: none;
                width: 80px;
                height: 80px;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
            }

            &.active {
                pointer-events: all;
                svg {
                    display: block;
                }
                &::before {
                    content: '';
                    position: absolute;
                    left: -10px;
                    top: -10px;
                    right: -10px;
                    bottom: -10px;
                    border: 10px solid #666;
                }
            }
        }
        .embroidery-inner {
            position: absolute;
            display: flex;

            &.active {
                pointer-events: all;
            }
        }
    }

    .embroidery-info {
        flex: 1;
    }

    .embroidery-colors {
        display: flex;
        flex-wrap: wrap;
        &::v-deep > span {
            margin: 0 5px;
        }
    }
}

.block {
    position: relative;
    padding: 50px 10px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;

    &::before {
        content: attr(name);
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        line-height: 40px;
        border-bottom: 1px solid #ddd;
        padding: 0 10px;
        box-sizing: border-box;
        font-size: 16px;
        color: #000;
    }
}

.embroidery-pattern {
    position: relative;
    padding: 50px 10px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
    .embroidery-pattern-title {
        display: flex;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        line-height: 40px;
        border-bottom: 1px solid #ddd;
        padding: 0 10px;
        box-sizing: border-box;
        font-size: 16px;
        color: #000;
        & > span {
            flex: 1;
        }

        & > div {
            margin-left: 10px;
        }

        &::v-deep .embroidery-buttons button {
            height: 30px;
        }
    }
    & > ul {
        display: flex;
        margin: 0 -5px;
        min-height: 100px;
        li {
            width: 100px;
            height: 100px;
            border: 1px solid #ddd;
            margin: 5px;
            border-radius: 5px;
            cursor: pointer;
            position: relative;

            .embroidery-preview {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
            }

            &:hover {
                border-color: #b32f61;
            }
            &.active {
                border-color: #b32f61;
            }
        }
    }
}

.embroidery-box {
    ul {
        display: flex;
        margin: 0 -5px;
    }
    li {
        width: 80px;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #ddd;
        margin: 5px;
        border-radius: 5px;
        cursor: pointer;

        &:hover {
            border-color: #b32f61;
        }
        &.active {
            border-color: #b32f61;
        }
    }
}

.embroidery-spu {
    display: flex;
    align-items: center;
    white-space: nowrap;
    margin-bottom: 10px;
    input {
        margin: 0 10px;
    }
}

.embroidery-colors {
    margin: 0 -5px 10px;
    .input-color {
        width: 30px;
        height: 30px;
        display: flex;
        position: relative;
        em {
            width: 100%;
            height: 100%;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        i {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            color: #fff;
            text-shadow: 0 0 3px rgba($color: #000000, $alpha: 0.5);
        }
    }
}

.embroidery-message {
    margin-bottom: 10px;
    background-color: #f1f1f1;
    padding: 10px;
    line-height: 24px;
    border-radius: 5px;
}
.embroidery-output {
    margin-bottom: 10px;
}

.input-picker {
    display: flex;
    flex-wrap: wrap;
    span {
        margin: 5px;
        width: 30px;
        height: 30px;
        position: relative;
        border-radius: 4px;
        overflow: hidden;
        border: 1px solid #ddd;
        cursor: pointer;
    }
}
</style>
